import React, { useEffect } from "react";
import { Modal, Form, Input, message } from "antd";
import { connect } from "react-redux";
import axios from "axios";
function PasswordEdit({ passwordVisible, setPassword, UpateUserInfo }) {
  const handleOk = function () {
    former
      .validateFields()
      .then(async (res) => {
        let { data: ql } = await axios.post("/api/editpassword", {
          oldpassword: res.oldpassword,
          password: res.newpassword,
          userid: UpateUserInfo.userInfo.id,
        });
        if (ql.ok !== 1) {
          return message.error(ql.message);
        }
        message.success(ql.message);
        handleCancel();
      })
      .catch((err) => {});
  };
  const handleCancel = function () {
    former.resetFields();
    setPassword(false);
  };
  const onFinish = function () {};
  const [former] = Form.useForm();
  const checkPassword = (rule, value, callback) => {
    return new Promise(function (resolve, reject) {
      if (value !== former.getFieldValue("newpassword")) {
        reject(new Error("2次密码不一致"));
      }
      resolve();
    });
  };
  useEffect(() => {
    // 通过判断 可以防止 former 没有渲染form元素没有成功绑定 就执行 设置表单值的情况
    if (passwordVisible) {
      former.setFieldsValue({ username: UpateUserInfo.userInfo.username });
    }
  }, [passwordVisible]);
  return (
    <Modal
      title="修改密码"
      visible={passwordVisible}
      onOk={handleOk}
      onCancel={handleCancel}
      okText="确认"
      cancelText="取消"
      className="pass"
    >
      <Form onFinish={onFinish} form={former} labelAlign="right" labelCol={{ span: 6 }}>
        <Form.Item label="用户名" name="username">
          <Input disabled></Input>
        </Form.Item>
        <Form.Item
          hasFeedback
          label="旧密码"
          name="oldpassword"
          rules={[
            { required: true, message: "旧密码必须填写" },
            { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: "不能有特殊字符" },
          ]}
        >
          <Input.Password></Input.Password>
        </Form.Item>
        <Form.Item
          hasFeedback
          label="新密码"
          name="newpassword"
          rules={[
            { required: true, message: "新密码必须填写" },
            { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: "不能有特殊字符" },
          ]}
        >
          <Input.Password></Input.Password>
        </Form.Item>
        <Form.Item
          hasFeedback
          label="确认新密码"
          name="isnewpassword"
          rules={[
            { required: true, message: "确认密码必须填写" },
            { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: "不能有特殊字符" },
            { validator: checkPassword },
          ]}
        >
          <Input.Password></Input.Password>
        </Form.Item>
      </Form>
    </Modal>
  );
}

export default connect((state) => state)(PasswordEdit);
